import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import http from '../utils/http.js';
import store from '../store'

NProgress.configure({
	showSpinner: false
});

Vue.use(VueRouter);

const routes = [{
		name: "login",
		path: "/login",
		component: resolve => require(["../view/login/Login.vue"], resolve)
	},

	{
		name: "home",
		path: "/home",
		component: resolve => require(["../view/home/Home.vue"], resolve),
		redirect: '/index',
		children: [{
			name: "index",
			path: "/index",
			component: resolve => require(["../view/index/Index.vue"], resolve),
			meta: {
				title: '首页',
				affix: true
			}
		}, 
		{
			name: "sysProfile",
			path: "/sysProfile",
			component: resolve => require(["../view/sys/user/profile.vue"], resolve),
			meta: {
				title: '个人中心'
			}
		},
		]
	},
	
	{
		path: "/",
		redirect: "/login"
	},
]

const router = new VueRouter({
	base: "/",
	routes,
	mode: "hash"
});

const whiteList = ['/login']
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
	NProgress.start();

	if (http.getToken()) {
		to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
		/* has token*/
		if (to.path === '/login') {
			next({
				path: '/index'
			})
		} else {
			if (store.state.sys.menuList == null) {
				store.dispatch('generateRoutes').then(accessRoutes => {
					// 根据roles权限生成可访问的路由表
					console.error("accessRoutes", accessRoutes)
					accessRoutes.forEach((item) => {
						router.addRoute("home", {
							name: item.name,
							path: item.path,
							component: item.component,
							meta: {
								title: item.name,
								affix: false
							}
						})
					})
					store.dispatch('dict/initDict')
					next({
						...to,
						replace: true
					}) // hack方法 确保addRoutes已完成
				})
			} else {
				next()
			}
		}
	} else {
		// 没有token
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next()
		} else {
			next(`/login`) // 否则全部重定向到登录页
		}
	}
});


router.afterEach(() => {
	NProgress.done();
	window.scrollTo(0, 0);
});

//重写路由的push方法 解决添加了重复的路由
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return routerPush.call(this, location).catch(error => error);
};

export default router;